package com.kcs.common.utils;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Pattern;

public class commonUtils {
	
    public static final String ddmmyyyyhhmmsswithslash = "dd/MM/yyyy HH:mm:ss";
    public static final String ddmmyyyywithslash = "dd/MM/yyyy";
    public static final String yyyymmdd = "yyyyMMdd";
    public static final String yyyymmddhhmmss = "yyyyMMddHHmmss";
    
	public static boolean isExistData(String sqlExist, ArrayList<String> condition, Connection conn){
		
		PreparedStatement statement = null;
		ResultSet result = null;
		
		try{
			statement = conn.prepareStatement(sqlExist);
			//SqlCreated.setWhereClaseInString(statement, condition);
			
			result = statement.executeQuery();
			
			while (result.next()) {
				int cnt = result.getInt(1);
				
				if(cnt > 0) 
					return true;
				else
					return false;
			}
			
		} catch(SQLException ex){
			ex.printStackTrace();
			LogWriter.error("Class commonUtils [Method : isExistData] error -->>> " + ex.getMessage(), Constant.LOGGER_COMMON);
		} finally {
            if (result != null) {
                try {
                	result.close();
                } catch (SQLException ex) {
                	LogWriter.error("Class commonUtils [Method : isExistData] error -->>> " + ex.getMessage(), Constant.LOGGER_COMMON);
                }
            }
            if (statement != null) {
                try {
                	statement.close();
                } catch (SQLException ex) {
                	LogWriter.error("Class commonUtils [Method : isExistData] error -->>> " + ex.getMessage(), Constant.LOGGER_COMMON);
                }
            }
		}
		return false;

	}
	
	public static Date stringToDate(String date, String format) throws Exception{
		
		Date toDate = null;
		
		if(date != null && !"".equals(date)){
			DateFormat df = new SimpleDateFormat(format);
			toDate = df.parse(date);
		}		
		
		return toDate;
	}
	
	public static String parseStringDateByFormat(String i_date, String i_format, String o_format) throws Exception {
		String o_date = null;
		
		if(i_date != null && !"".equals(i_date)){
			Date date = stringToDate(i_date, i_format);
			
			o_date = formatDate(date, o_format);
		}		
		
		return o_date;
	}
	
	public static String formatDate(Date date, String strformat) {

		// Set Locale for format CE
		String str = "";
		if (date == null) {
			return str;
		} else {
			SimpleDateFormat formatter = new SimpleDateFormat(strformat,Locale.US);
			str = formatter.format(date);
		}

		return str;
	}
	
	public static Date getCurrentDate(){
		Date date = new Date();
		
		return date;
	}
	
	public static String convertFormatDate(String date, String oldformat, String newformat) {

		String str = "";

		try {

			if (date == null || date.equals("")) {
				return str;
			} else {
				
				SimpleDateFormat formatter = new SimpleDateFormat(oldformat);
				Date newdate = (Date) formatter.parse(date);

				SimpleDateFormat newformatter = new SimpleDateFormat(newformat);
				str = newformatter.format(newdate);

			}
		} catch (Exception e) {
			e.printStackTrace();
			LogWriter.error("Class commonUtils [Method : convertFormatDate] error -->>> " + e.getMessage(), Constant.LOGGER_COMMON);
		}

		return str;
	}

	/*Convert String to Date (dd/mm/yyyy hh:mm:ss)*/
	public static Date convertStrtoDate_HHMMSS(String date, String format) {
		GregorianCalendar calendar = new GregorianCalendar(Locale.US);
		int year = 1900;
		int month = 0;
		int day = 1;
		int hourOfDay = 24;
		int minute = 60;
		int second = 60;
		
		try {
			String newDate = convertFormatDate(date, format, "dd/MM/yyyy hh:mm:ss");
			String[] dateArr = newDate.split("/");
			day = Integer.parseInt(dateArr[0]);
			month = Integer.parseInt(dateArr[1]) - 1;
			
			String[] time = String.valueOf(dateArr[2]).split(":");
			year = Integer.parseInt(dateArr[2].substring(0, 4));
			hourOfDay = Integer.parseInt(time[0].substring(5));
			minute = Integer.parseInt(time[1]);
			second = Integer.parseInt(time[2]);
			calendar.clear();
			calendar.set(year, month, day, hourOfDay, minute, second);
		} catch (Exception e) {
			return calendar.getTime();
		}

		return calendar.getTime();
	}
	
	public static int convert_ddmmyyyy2int(String strDate) {
		try {
			String date = "";
			String month = "";
			String year = "";

			if (!isValidDateFormat(strDate)) {
				return 0;
			}

			int length = (strDate == null ? 0 : strDate.length());
			switch (length) {
			case 6:
				if (Pattern.matches("\\d/\\d/\\d{2}", strDate)) {
					date = "0" + strDate.substring(0, 1);
					month = "0" + strDate.substring(2, 3);
					year = "20" + strDate.substring(4);

					return Integer.parseInt(year + month + date);

				}
				if (Pattern.matches("\\d{2}\\d{2}\\d{2}", strDate)) {
					date = strDate.substring(0, 2);
					month = strDate.substring(2, 4);
					year = "20" + strDate.substring(4);

					return Integer.parseInt(year + month + date);
				}
				return 0;

			case 7:
				if (Pattern.matches("\\d{1,2}/\\d{1,2}/\\d{2}", strDate)) {
					if (strDate.indexOf("/") == 2) {
						date = strDate.substring(0, 2);
						month = "0" + strDate.substring(3, 4);
						year = "20" + strDate.substring(5);

						return Integer.parseInt(year + month + date);
					}
					date = "0" + strDate.substring(0, 1);
					month = strDate.substring(2, 4);
					year = "20" + strDate.substring(5);

					return Integer.parseInt(year + month + date);
				}
				return 0;

			case 8:
				if (Pattern.matches("\\d{2}/\\d{2}/\\d{2}", strDate)) {
					date = strDate.substring(0, 2);
					month = strDate.substring(3, 5);
					year = "20" + strDate.substring(6);

					return Integer.parseInt(year + month + date);
				}
				if (Pattern.matches("\\d/\\d/\\d{4}", strDate)) {
					date = "0" + strDate.substring(0, 1);
					month = "0" + strDate.substring(2, 3);
					year = strDate.substring(4);

					return Integer.parseInt(year + month + date);
				}
				if (Pattern.matches("\\d{2}\\d{2}\\d{4}", strDate)) {
					date = strDate.substring(0, 2);
					month = strDate.substring(2, 4);
					year = strDate.substring(4);

					return Integer.parseInt(year + month + date);
				}
				return 0;
			case 10:
				if (Pattern.matches("\\d{2}/\\d{2}/\\d{4}", strDate)) {
					date = strDate.substring(0, 2);
					month = strDate.substring(3, 5);
					year = strDate.substring(6);

					return Integer.parseInt(year + month + date);
				}
				return 0;

			default:
				return 0;
			}

		} catch (Exception e) {
			return 0;
		}
	}
	
	
	public static boolean isNumeric(String str) {

		boolean ret = true;
		boolean havedot = false;
		boolean havedigit = false;
		int pos = 0;
//		boolean isDouble = false;

		str = trimAll(str);
		if (str.equals(""))
			return false;
		
		/*try {
			str = Pattern.compile(",").matcher(str).replaceAll("");
			// check isDouble?
			double nb = Double.parseDouble(str);
			
			DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(Locale.US);
		    String nbStr = Double.toString(nb);
		    try {
		    	// Convert to numeric all number. (1.0E7 ==> 10000000)
				Number pNum = nf.parse(nbStr);
				str = pNum.toString();
			} catch (ParseException e) {
				return false;
			}
			isDouble = true;
		}catch(NumberFormatException ex){
			return false;
		}*/
		
		/*if (isDouble){*/
				try {
				StringBuffer sb = new StringBuffer(str);
				if (sb.charAt(0) == ',') {
					ret = false;
				} else {
					if (sb.indexOf(".") < 0) {
						havedot = true;
					}
					for (int i = sb.length() - 1; i >= 0; i--) {
						switch (sb.charAt(i)) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							havedigit = true;
							if (havedot) {
								pos++;
							}
							break;
						case '.':
							if (havedot) {
								ret = false;
							} else {
								havedot = true;
							}
							break;
						case ',':
							if ((pos == 0) || (pos % 3 != 0)) {
								ret = false;
							}
							break;
						default:
							ret = false;
						}
						if (!ret) {
							break;
						}
					}
					if (!havedigit) {
						ret = false;
					}
				}
			} catch (Exception e) {
				ret = false;
			}
		/*}*/
		return ret;
	}
	
	public static BigDecimal convertStrtoBigDecimal(String str) {
		BigDecimal result = null;

		if (str == null || str.equals("")) {
			result = new BigDecimal(0);
		} else if (isNumeric(str)) {
			result = new BigDecimal(Pattern.compile(",").matcher(str)
					.replaceAll(""));
		}
		return result;
	}
	
	public static boolean isValidDateFormat(String strDate) {
		try {
			int date = 0;
			int month = 0;
			int year = 0;
			int[] monthLength = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
			
			// date length should be 10 characters (no more no less) 
		    if (strDate.length() != 10) { 
		        return false; 
		    } 

		    // third and sixth character should be '/' 
		    if (!strDate.substring(2, 3).equals("/") || !strDate.substring(5, 6).equals("/")) { 
		        return false; 
		    } 

			if (Pattern.matches("\\d{2}/\\d{2}/\\d{4}", strDate)) {
				date = Integer.parseInt(strDate.substring(0, 2));
				month = Integer.parseInt(strDate.substring(3, 5));
				year = Integer.parseInt(strDate.substring(6));
				
				// Check the ranges of month and year
				if ((year < 2000) || (year > 3000) || month == 0 || month > 12) {
					return false;
				}
				
				// Adjust for leap years
				if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
				       monthLength[1] = 29;
				// Check the range of the day
				return date > 0 && date <= monthLength[month - 1];
			}
			
			return false;

		} catch (Exception e) {
			return false;
		}
	}
	
	public static String trimAll(String str) {

		if (str == null)
			return "";
		
		return str.trim();
	}
	
	public static String getStyleString(String str) {
		if (str != null && str.equals(Constant.ERR_ATTR)) {
			return "style=\"color:red;background-color:#ffff00;\"";
		} else {
			return "";
		}
	}
	
	public static String getDir()
	{
		final File dir = new File ("."); 		
		String localPath = "";
		try {
			localPath = dir.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
			
		}
		return localPath ;
	}
	
	public static String formatNumber(Double number, int s, String appendText, boolean isComma) {
		StringBuffer sf = new StringBuffer();
		if (s == 0) {
			if(isComma)
				sf.append("###,##0");
			else
				sf.append("#####0");			
		} else {
			if(isComma)
				sf.append("###,##0.");
			else
				sf.append("#####0.");
		}
		int i = 0;
		while (i < s) {
			sf.append(appendText);
			i++;
		}
		DecimalFormat formatter = new DecimalFormat(sf.toString());
		return formatter.format(number);
	}
	
	
	 public static void main(String args[]) {
		
//		boolean tf = commonUtils.isNumeric("10,000,000");
//		System.out.println(tf);
		
		
		  /* double aDouble = 1.0E7;
		    DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(Locale.US);
		    String aString = Double.toString(aDouble);
		    try {
				Number aa = nf.parse(aString);
				aa.toString();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		 
		 String s = "999999900.00";
		 try {
			System.out.println(decimalFormat(s));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	 }   
	 
	 public static java.sql.Date convertUtilDatetoSQLDate(java.util.Date utilDate) throws Exception {
		 java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
		 
		 if(utilDate != null) sqlDate = new java.sql.Date(utilDate.getTime());
		 
		 return sqlDate;
	 }
	 
	 public static java.util.Date convertSQLDatetoUtilDate(java.sql.Date sqlDate) throws Exception {
		 java.util.Date utilDate = getCurrentDate();
		 
		 if(sqlDate != null) utilDate = new java.util.Date(sqlDate.getTime());
		 
		 return utilDate;
	 }
	 
	 public static java.sql.Date convertStringtoSQLDate(String date, String formatDate) throws Exception {
		 SimpleDateFormat format 	= new SimpleDateFormat(formatDate);
		 java.sql.Date sql 			= null;
		 
		 if(date != null && !"".equals(date)){
			 Date parsed = format.parse(date);
			 sql 		 = new java.sql.Date(parsed.getTime());
		 }
		 
		 return sql;
	 }
	 
	 public static String setFilter(Object obj) throws Exception {
		 
		String result = "";
		
		if(obj != null)
			result = "%" + obj + "%";
		
		return result;
	 }
	 
	 //-- 09/10/2013 by Aon
	 public static boolean checkDateFormat(String date){ //---- dd/mm/YYYY
		boolean result = false;
		String[] spl = date.split("/");
		int d = 0;
		int m = 0;
		int y = 0;
		
		try{
			if(spl.length == 3){
				if(spl[0].length() == 1 || spl[0].length() == 2){
					if(spl[1].length() == 1 || spl[1].length() == 2){
						if(spl[2].length() == 4){
							d = Integer.parseInt(spl[0]);
							m = Integer.parseInt(spl[1]);
							y = Integer.parseInt(spl[2]);
							
							result = true;
						}
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return result;
	}
	 
	//-- 09/10/2013 by Aon
	public static boolean checkBetweenDate(String startDate, String endDate){ //--- dd/mm/YYYY
		boolean result = false;
		String[] splStart = null;
		String[] splEnd = null;
		int startD = 0;
		int startM = 0;
		int startY = 0;
		int endD = 0;
		int endM = 0;
		int endY = 0;
		
		try{
			if(checkDateFormat(startDate) && checkDateFormat(endDate)){
				splStart = startDate.split("/");
				splEnd = endDate.split("/");
				
				startD = Integer.parseInt(splStart[0]);
				startM = Integer.parseInt(splStart[1]);
				startY = Integer.parseInt(splStart[2]);
				
				endD = Integer.parseInt(splEnd[0]);
				endM = Integer.parseInt(splEnd[1]);
				endY = Integer.parseInt(splEnd[2]);
				
				if(endY > startY){
					result = true;
				}else if(endY == startY){
					if(endM > startM){
						result =true;
					}else if(endM == startM){
						if(endD >= startD){
							result = true;
						}
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return result;
	}
	
	//-- 10/10/2013 by Aon
	public static java.sql.Date convertYYYYMMDDToSQLDate(String strDate){
		//-- example : 20130422
		if(strDate != null){
			String dd = strDate.substring(6,8);
			String mm = strDate.substring(4,6);
			String yyyy = strDate.substring(0,4);			
			Calendar c = Calendar.getInstance();
			
			c.set(Integer.parseInt(yyyy), Integer.parseInt(mm)-1, Integer.parseInt(dd));

			return new java.sql.Date(c.getTimeInMillis());
		}else{
			return null;
		}
	}
	
	//-- 15/10/2013 by Aon
	public static final String decimalFormat(BigDecimal dcm)throws Exception{
		DecimalFormat df = null;
		if(dcm != null){
			df = new DecimalFormat("#,##0.00");
			return df.format(dcm);
		}else{
			return "0.00";
		}
	}
	public static final String decimalFormat(String s)throws Exception{
		DecimalFormat df = null;
		BigDecimal dcm = null;
		if(s != null){
			df = new DecimalFormat("#,##0.00");
			dcm = new BigDecimal(s.replaceAll(",",""));
			return df.format(dcm);
		}else{
			return "0.00";
		}
	}
	
	//-- 15/10/2013 by Aon
	public static String like(String s)throws Exception{
		return (s==null||s.equals(""))?"%":"%"+s+"%";
	}

}

	
